#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_errno.h"
#include "iot_uart.h"
#include "hi_uart.h"
#include "hi_io.h"
#include "hi_gpio.h"


//IoTGpioInit专用
#define GPIO_PIN_INIT    1
#define GPIO_PIN_UNINIT  0
static unsigned char g_gpioMap[HI_GPIO_IDX_MAX] = {0};
static unsigned char g_gpioInitNum = 0;




#define UART_BUFF_SIZE 1024
#define UART_PORT 1


unsigned int IoTGpioInit(unsigned int id)
{
    if (id >= HI_GPIO_IDX_MAX) {
        return IOT_FAILURE;
    }

    if (g_gpioInitNum == 0) {
        (void)hi_gpio_init();
    }

    if (g_gpioMap[id] == GPIO_PIN_INIT) {
        return IOT_FAILURE;
    } else {
        g_gpioMap[id] = GPIO_PIN_INIT;
        g_gpioInitNum++;
    }

    return IOT_SUCCESS;
}

unsigned int IoTUartInit(unsigned int id, const IotUartAttribute *param)
{
    hi_uart_attribute attr = {0};
    hi_uart_extra_attr extraAttr = {0};

    if (NULL == param) {
        return IOT_FAILURE;
    }

    attr.baud_rate = param->baudRate;
    attr.data_bits = param->dataBits;
    attr.pad = param->pad;
    attr.parity = param->parity;
    attr.stop_bits = param->stopBits;

    if (IOT_UART_BLOCK_STATE_NONE_BLOCK == param->rxBlock) {
        extraAttr.rx_block = HI_UART_BLOCK_STATE_NONE_BLOCK;
    } else {
        extraAttr.rx_block = HI_UART_BLOCK_STATE_BLOCK;
    }

    if (IOT_UART_BLOCK_STATE_NONE_BLOCK == param->txBlock) {
        extraAttr.tx_block = HI_UART_BLOCK_STATE_NONE_BLOCK;
    } else {
        extraAttr.tx_block = HI_UART_BLOCK_STATE_BLOCK;
    }

    return hi_uart_init((hi_uart_idx)id, &attr, &extraAttr);
}


int Uart_ReceiveData(char *data, unsigned int len)
{
    uint16_t rxlen =0 ;
    int ret = 0;
    while(len - rxlen > 0)
    {
        ret = hi_uart_read_timeout(UART_PORT, (unsigned char *)data+rxlen, len-rxlen, 20);
        if(ret == 0 && rxlen != 0)
        {
            return rxlen;
        }
        else
        {
            rxlen += ret;
        }
    }
    return rxlen;
}

int Uart_SentData(char *data, unsigned int len)
{
    int ret;
    //ret = IoTUartWrite(UART_PORT, (unsigned char *)data, len);
    ret = hi_uart_write(UART_PORT, (unsigned char *)data, len);
    if(ret == -1)
    {
        printf("Uart write data error!\r\n");
    }
    return ret;
}

void UART_Init(void)
{
    uint32_t ret;

    IotUartAttribute uart_attr = {
        //波特率115200d、数据位8、停止位1、无奇偶检验位
        .baudRate = 115200,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
        .rxBlock = 1,
    };

    IoTGpioInit(HI_GPIO_IDX_5);//初始化GPIO5
    IoTGpioInit(HI_GPIO_IDX_6);//初始化GPIO6

    hi_io_set_func(HI_GPIO_IDX_5, HI_IO_FUNC_GPIO_5_UART1_RXD);
    hi_io_set_func(HI_GPIO_IDX_6, HI_IO_FUNC_GPIO_6_UART1_TXD);
    //初始化串口
    ret = IoTUartInit(UART_PORT, &uart_attr);
    if (ret != IOT_SUCCESS)
    {
        printf("Failed to init uart%d.", UART_PORT);
        return;
    }

}
